package com.lw.leetcode.arr.b;

import java.util.TreeMap;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 1296. 划分数组为连续数字的集合
 * 846. 一手顺子
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/13 16:43
 */
public class IsPossibleDivide {
    public static void main(String[] args) {
        IsPossibleDivide test = new IsPossibleDivide();
        // true
        int[] arr = {1, 2, 3, 3, 4, 4, 5, 6};
        int k = 4;

        // true
//        int[] arr = {3, 2, 1, 2, 3, 4, 3, 4, 5, 9, 10, 11};
//        int k = 3;

        boolean possibleDivide = test.isPossibleDivide(arr, k);
        System.out.println(possibleDivide);
    }

    public boolean isPossibleDivide(int[] nums, int k) {
        int length = nums.length;
        if (length % k != 0) {
            return false;
        }

        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int num : nums) {
            map.merge(num, 1, (a, b) -> a + b);
        }
        int c = length / k;

        Integer key = map.firstKey();

        while (c > 0) {
            Integer item = 0;
            boolean flag = true;
            for (int i = 0; i < k; i++) {
                Integer count = map.get(key);
                if (count == null || count == 0) {
                    return false;
                }
                map.put(key, count - 1);
                if (flag && count - 1 != 0) {
                    flag = false;
                    item = key;
                }
                key++;
            }
            if (flag) {
                item = map.ceilingKey(key);
            }
            key = item;
            c--;
        }
        return true;
    }


    public boolean isNStraightHand(int[] nums, int k) {
        int length = nums.length;
        if (length % k != 0) {
            return false;
        }

        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int num : nums) {
            map.merge(num, 1, (a, b) -> a + b);
        }
        int c = length / k;

        Integer key = map.firstKey();

        while (c > 0) {
            Integer item = 0;
            boolean flag = true;
            for (int i = 0; i < k; i++) {
                Integer count = map.get(key);
                if (count == null || count == 0) {
                    return false;
                }
                map.put(key, count - 1);
                if (flag && count - 1 != 0) {
                    flag = false;
                    item = key;
                }
                key++;
            }
            if (flag) {
                item = map.ceilingKey(key);
            }
            key = item;
            c--;
        }
        return true;
    }

}
